package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.EnrollList;
import com.xmy.cultivate.entity.views.FirstSignUp;
import com.xmy.cultivate.entity.views.IncomeDayReport;
import com.xmy.cultivate.entity.views.ResApplyGather;
import com.xmy.cultivate.enums.OrderTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ConfigData;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.ResultCode;
import org.apache.ibatis.annotations.Param;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单报名信息 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-01
 */
@Service
public class OrderDetailServiceImpl extends ServiceImpl<OrderDetailMapper, OrderDetail> implements IOrderDetailService {

    @Autowired
            @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    CourseMapper courseMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    IStudentTypeService iStudentTypeService;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    @Lazy
    IEnrollInfoService iEnrollInfoService;

    @Autowired
    @Lazy
    IOrderApplyService iOrderApplyService;

    @Autowired
    @Lazy
    ICoursePricingService iCoursePricingService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    @Lazy
    IRenewDataService iRenewDataService;

    @Autowired
    @Lazy
    IOrderTransferService iOrderTransferService;

    @Autowired
    @Lazy
    IOrderTransferDetailService iOrderTransferDetailService;


    public IPage<EnrollList> getEnrollList(IPage<?> page, Wrapper wrapper){
        IPage<EnrollList> enrollListIPage = orderDetailMapper.getEnrollList(page,wrapper);
        for (EnrollList enrollList:enrollListIPage.getRecords()){
            Course course = courseMapper.selectById(enrollList.getCourseId());
            if(course!=null){
                enrollList.setSubjectsId(course.getSubjectsId());
                //System.out.print("---"+enrollList.getSchoolId()+"="+enrollList.getStudentId()+"="+course.getId());
                boolean isNew = iStudentTypeService.isNew(enrollList.getSchoolId(),enrollList.getStudentId(),course.getSubjectsId());
                if(isNew){
                    enrollList.setIsNewStudent(1);
                }else {
                    enrollList.setIsNewStudent(2);
                }
            }
        }

        return enrollListIPage;
    }

    public Map<String, BigDecimal> enrollListMoney(Wrapper wrapper){
        BigDecimal solidPrice = orderDetailMapper.getSolidPrice(wrapper);
        BigDecimal studentCount = orderDetailMapper.getAllStudentCount(wrapper);

        Map<String,BigDecimal> map = new HashMap<>();
        map.put("solidPrice",solidPrice);
        map.put("studentCount",studentCount);
        return map;
    }


    public List<OrderDetail> orderDetail(Wrapper wrapper){
        return  orderDetailMapper.orderDetail(wrapper);
    }

    public Integer getApplyCountForSubjects(Long schoolId,Long studentId,Long subjectsId,Integer newYeartPart,Integer newNum){
        return orderDetailMapper.getApplyCountForSubjects(schoolId,studentId,subjectsId,newYeartPart,newNum);
    }

    public OrderDetail getLastOneForStudent(Long schoolId,Long studentId,Long subjectsId){
        return orderDetailMapper.getLastOneForSubjectId(schoolId,studentId,subjectsId);
    }
    /**
     * 办理中心获取学员报读信息
     * @return
     */
    public List<OrderDetail> GetLessonByStuInfoId(Wrapper wrapper){
        return orderDetailMapper.GetLessonByStuInfoId(wrapper);
    }

    public List<Subjects> GetSubjectsByStuInfoId(Wrapper wrapper){

        List<Subjects> subjectsList = orderDetailMapper.GetSubjectsByStuInfoId(wrapper);
        for (Subjects subjects:subjectsList){
            Organization organization = organizationMapper.selectById(subjects.getSchoolId());
            Course course = courseMapper.selectById(subjects.getCourseId());
            if(organization !=null){
                subjects.setSchoolName(organization.getName());
                if(course != null){
                    subjects.setYearClassId(course.getYearClassId().getKey());
                }
            }
        }
        return  subjectsList;
    }

    public List<OrderDetail> getLessonByCourseId(Long courseId,Long studentId,Long schoolId){
        return orderDetailMapper.getLessonByCourseId(courseId,studentId,schoolId);
    }

    /**
     * 报读通过科目，获取在读信息
     * @param subjectsId
     * @param studentId
     * @return
     */
    public List<OrderDetail> getLessonForSubjects(Long subjectsId,Long studentId,Long schoolId){
        return orderDetailMapper.getLessonForSubjects(subjectsId,studentId,schoolId);
    }

    public List<Organization> getSignUpSchoolListForWhere(@Param(Constants.WRAPPER) Wrapper wrapper){
        return orderDetailMapper.getSignUpSchoolListForWhere(wrapper);
    }

    public FirstSignUp getFirstSignUp(Long studentId, Long gradeId, Integer count){
        return orderDetailMapper.getFirstSignUp(studentId,gradeId,count);
    }

    public Boolean stopCourse(Long orderDetailId){

        OrderDetail orderDetail = orderDetailMapper.selectById(orderDetailId);
        if(orderDetail == null){
            throw new CommonException(ResultCode.ORDERDETAIL_NOT);
        }

        if(orderDetail.getReadingStatus() != ReadingStatusEnum.IN_READING){
            throw new CommonException(ResultCode.STATUSNOT);
        }
        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("order_id",orderDetail.getOrderId()).ne("status",2);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailQueryWrapper);


        for (OrderDetail orderDetailTemp:orderDetailList){

        }
        return true;
    }

    public IPage<IncomeDayReport> getIncomeDayReport(IPage<?> page, Wrapper wrapper){
        IPage<IncomeDayReport> iPage = orderDetailMapper.getIncomeDayReport(page,wrapper);
        for (IncomeDayReport incomeDayReport:iPage.getRecords()){
            if(incomeDayReport.getGradeId()!=null){
                Grade grade = gradeMapper.selectById(incomeDayReport.getGradeId());
                Course course = courseMapper.selectById(incomeDayReport.getCourseId());
                if(grade !=null){
                    incomeDayReport.setGradeName(grade.getName());
                    Staff staff = staffMapper.selectById(grade.getTeacherId());
                    if(staff!=null){
                        incomeDayReport.setTeacherName(staff.getName());
                    }
                }
                if(course!=null){
                    incomeDayReport.setSubjectsName(ConfigData.getSubjectsNameForNum(Integer.parseInt(course.getSubjectsId().toString())));
                }
            }

            /**
             * 邀约人
             */
            List<String> inviteNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(),1);
            /**
             * 试听人
             */
            List<String> auditionNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(),2);
            /**
             * 成交人
             */
            List<String> bargainNameList = iEnrollInfoService.getEnrollTeacher(incomeDayReport.getOrderId(),3);

            incomeDayReport.setInviteNames(String.join(",",inviteNameList));
            incomeDayReport.setAuditionNames(String.join(",",auditionNameList));
            incomeDayReport.setBargainNames(String.join(",",bargainNameList));

            Course course = courseMapper.selectById(incomeDayReport.getCourseId());
            incomeDayReport.setYearClassName(ConfigData.getYearClassForNum(course.getYearClassId().getKey()));
        }

        return iPage;
    }



    public List<OrderDetail> getBigFifteeList(){
        return orderDetailMapper.getBigFifteeList();
    }

    public Integer getUseCourseHouse(Wrapper wrapper){
        return orderDetailMapper.getUseCourseHouse(wrapper);
    }


    /**
     * 课程顺延
     */
    @Test
    public void courseAuto(){

        Integer oldVersion = 0;
        Integer afterVersion = 1;
        Integer yearAndQuarter = 20233;//被顺延的年份与学期

        Integer plusClassNum = 0;//年级是否要增加，1为增加一个年级

        Integer nextQuarterNum = 4;


        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_and_quarter",yearAndQuarter);
        orderDetailQueryWrapper.gt("residue_course_count",0);
        orderDetailQueryWrapper.eq("version",oldVersion);
        orderDetailQueryWrapper.ne("status",2);
        orderDetailQueryWrapper.orderByAsc("school_id");
        //orderDetailQueryWrapper.last("limit 10");
        Long count =  this.count(orderDetailQueryWrapper);

        //System.out.println("count:"+count);

        List<OrderDetail> orderDetailList = this.list(orderDetailQueryWrapper);
        Integer j = 0;
        for(OrderDetail orderDetailOld:orderDetailList){
            try {
                Organization organization = organizationMapper.selectById(orderDetailOld.getSchoolId());
                Course courseOld = courseMapper.selectById(orderDetailOld.getCourseId());
                OrderApply orderApplyOld = iOrderApplyService.getById(orderDetailOld.getOrderId());

                QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
                courseQueryWrapper.eq("subjects_id",courseOld.getSubjectsId());
                //courseQueryWrapper.eq("year_class_id",courseOld.getYearClassId().getKey()+1);//年级加1
                courseQueryWrapper.eq("year_class_id",courseOld.getYearClassId().getKey()+plusClassNum);//年级加1
                courseQueryWrapper.eq("quarter_num",nextQuarterNum);//顺延到暑假班
                courseQueryWrapper.eq("status",1);//状态为开启的
                courseQueryWrapper.and(i->i.eq("opening_school_type",1).or().inSql("id","select for_id from appoint_school where type = 1 and school_id= "+orderDetailOld.getSchoolId()+" "));

                courseQueryWrapper.last("limit 1");

                Course course = courseMapper.selectOne(courseQueryWrapper);
                if(course == null){
                    //System.out.println("课程为空");
                    //System.out.println(organization.getName()+"原课程："+courseOld.getName()+"--年级："+courseOld.getYearClassId().getKey()+"studnetId:"+orderDetailOld.getStudentId());
                    continue;
                }


                QueryWrapper<CoursePricing> coursePricingQueryWrapper = new QueryWrapper<>();

                if(course.getOpeningSchoolType().getKey().equals(1)){
                    //select id from course_price_school where course_id = and school_id =
                    coursePricingQueryWrapper.inSql("price_school_id","select id from course_price_school where course_id = "+course.getId()+" and school_id =0 and deleted=0");
                }else {
                    coursePricingQueryWrapper.inSql("price_school_id","select id from course_price_school where course_id = "+course.getId()+" and school_id ="+orderDetailOld.getSchoolId()+" and deleted=0");

                }

                if((orderDetailOld.getResidueCourseCount()%45) == 0){
                    coursePricingQueryWrapper.eq("count",45);
                }else {
                    coursePricingQueryWrapper.eq("count",3);
                }
                //coursePricingQueryWrapper.eq("status",1);
                coursePricingQueryWrapper.last("limit 1");


                CoursePricing coursePricing = iCoursePricingService.getOne(coursePricingQueryWrapper);

                if(coursePricing ==null){
                    //System.out.println("没有找到课程价格数据");
                    continue;
                }

                LocalDate nowDate = LocalDate.now();

                //新数据
                OrderApply orderApply = new OrderApply();
                Long orderId = idWorker.nextId();
                orderApply.setId(orderId);
                orderApply.setVersion(1);
                int [] randMath = new int[]{1,2,3,4,5,6,7,8,9,0};
                Integer randReceiptNo = CommonUtil.getNotSimple(randMath,7);
                orderApply.setReceiptNo(randReceiptNo.toString());

                BigDecimal unitPrice = coursePricing.getUnitPrice();

                //应收
                BigDecimal price = new BigDecimal(orderDetailOld.getResidueCourseCount()).divide(new BigDecimal(3),BigDecimal.ROUND_UP).multiply(unitPrice);

                BigDecimal residuePrice = orderDetailOld.getResiduePrice();//收入为剩余金额
                BigDecimal solidPrice = new BigDecimal(0);
                //BigDecimal disPrice = price.subtract(residuePrice);
                BigDecimal disPrice = new BigDecimal(0);

                orderApply.setPrice(residuePrice);//应收为剩余费用
                orderApply.setSolidPrice(residuePrice);
                if(disPrice.compareTo(BigDecimal.ZERO)>0){
                    orderApply.setDiscountsDate(nowDate);
                }
                orderApply.setDisPrice(disPrice);
                orderApply.setTransferPrice(new BigDecimal(0));//转课抵扣金额,取消使用residuePrice
                orderApply.setStudentId(orderDetailOld.getStudentId());
                orderApply.setSchoolId(orderApplyOld.getSchoolId());
                orderApply.setHandleSchoolId(orderApplyOld.getHandleSchoolId());
                orderApply.setHandleSchoolName(orderApplyOld.getHandleSchoolName());
                orderApply.setHandleDate(nowDate);
                orderApply.setHandlePersonId(orderApplyOld.getHandlePersonId());
                orderApply.setHandlePersonName(orderApplyOld.getHandlePersonName());
                orderApply.setCreatedId(orderApplyOld.getCreatedId());
                orderApply.setOrderType(OrderTypeEnum.ORDER_TYPE_TRANSFER);
                orderApply.setApplyType(OrderTypeEnum.ORDER_TYPE_TRANSFER);



                String tradeContent = "";//交易内容，交易详情,如：八年级英语【夏季班】，2500元(30课时)*1=2500元，学费优惠100元
                Course outCourse = courseMapper.selectById(orderDetailOld.getCourseId());
                tradeContent += "转出："+outCourse.getName()+","+orderDetailOld.getResidueCourseCount()+"课时,"+orderDetailOld.getResiduePrice()+"元";


                tradeContent += "</br>转入：";

                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setId(idWorker.nextId());
                orderDetail.setOrderId(orderApply.getId());
                orderDetail.setSchoolId(orderDetailOld.getSchoolId());//所属校区
                orderDetail.setStudentId(orderDetailOld.getStudentId());
                orderDetail.setCourseId(course.getId());
                orderDetail.setCourseName(course.getName());
                orderDetail.setSubjectsId(course.getSubjectsId());
                orderDetail.setCoursePriceId(coursePricing.getId());

                orderDetail.setCount(orderDetailOld.getResidueCourseCount()/coursePricing.getCount());//单位数量
                orderDetail.setAllCourseCount(orderDetailOld.getResidueCourseCount());//总课时
                orderDetail.setUseCourseCount(0);
                orderDetail.setResidueCourseCount(orderDetailOld.getResidueCourseCount());//剩余课时
                orderDetail.setCourseHouse(orderDetailOld.getCourseHouse());

                orderDetail.setPrice(residuePrice);//收入为剩余金额
                orderDetail.setSolidPrice(orderDetail.getPrice());
                orderDetail.setResiduePrice(orderDetail.getSolidPrice().subtract(disPrice));
                orderDetail.setDiscountsPrice(disPrice);
                orderDetail.setDiscountsDate(nowDate);
                orderDetail.setServePrice(coursePricing.getServePrice());
                orderDetail.setMaterialsPrice(new BigDecimal(0));
                orderDetail.setEnrollType(1);
                orderDetail.setYearClassId(course.getYearClassId().getKey());

                orderDetail.setHandleDate(orderApply.getHandleDate());
                orderDetail.setOrderType(orderApply.getOrderType());

                //添加当前报读的续班信息
                Integer year_part = iQuarterService.getQuarterYearPartForNum(course.getQuarterNum());//获取报读的年份

                orderDetail.setYearPart(year_part);
                //设置报读的季度
                orderDetail.setQuarterNum(course.getQuarterNum());
                //年份与季度
                orderDetail.setYearAndQuarter(Integer.parseInt(year_part+""+course.getQuarterNum()));
                tradeContent += course.getName()+",";

                tradeContent += orderDetail.getPrice();

                if(orderDetail.getCoursePriceId()!=null){
                    if(coursePricing != null){
                        tradeContent +="("+coursePricing.getCountUnit()+")*"+orderDetail.getCount()+"="+orderDetail.getPrice()+"元";
                        orderDetail.setCoursePriceName(coursePricing.getCount()+coursePricing.getCountUnit()+"="+coursePricing.getAllPrice()+"元");

                        //保存到订单支付价格表
                        OrderCoursePricing orderCoursePricing = new OrderCoursePricing();

                        orderCoursePricing.setId(orderDetail.getId());
                        orderCoursePricing.setPrice(coursePricing.getPrice());
                        orderCoursePricing.setCount(coursePricing.getCount());
                        orderCoursePricing.setCountUnit(coursePricing.getCountUnit());
                        orderCoursePricing.setUnitPrice(coursePricing.getUnitPrice());
                        orderCoursePricing.setChargeMode(coursePricing.getChargeMode());
                        orderCoursePricing.setServePrice(coursePricing.getServePrice());
                        orderCoursePricing.setMaterialsPrice(coursePricing.getMaterialsPrice());
                        orderCoursePricing.setAllPrice(coursePricing.getAllPrice());
                        iOrderCoursePricingService.saveOrUpdate(orderCoursePricing);
                    }
                }


                //iOrderDetailService.save(orderDetail);

                //设置为新生或者老生
                iStudentTypeService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course.getSubjectsId(),1);

                //更新续班信息是否成功
                //转课
                Grade grade = null;
                iRenewDataService.updateData(orderDetail.getSchoolId(),orderDetail.getStudentId(),course,grade,orderDetail.getAllCourseCount(),2,orderDetail.getId());

                iRenewDataService.addData(orderDetail.getSchoolId(),orderDetail.getStudentId(),year_part,course,grade);

                orderApply.setYearPart(year_part);
                orderApply.setQuarterNum(course.getQuarterNum());
                orderApply.setTradeContent(tradeContent);


                //orderDetailOld.setReadingStatus(ReadingStatusEnum.TURN);
                orderDetailOld.setAutoOutHouse(orderDetailOld.getResidueCourseCount());
                orderDetailOld.setResidueCourseCount(0);
                orderDetailOld.setResiduePrice(new BigDecimal(0));

                orderDetailOld.setRollOutHouse(orderDetail.getResidueCourseCount()+orderDetailOld.getRollOutHouse());
                orderDetailOld.setRollOutPrice(orderDetail.getResiduePrice().add(orderDetailOld.getRollOutPrice()));

                orderDetailOld.setVersion(afterVersion);//被顺延的数据
                orderDetailMapper.updateById(orderDetailOld);
                orderDetail.setVersion(0);//新学期的数据版本为0开始
                orderDetailMapper.insert(orderDetail);


                Long transferCourseId = null;
                //Boolean isAll = true;//是否全部转出
                OrderTransfer orderTransfer = new OrderTransfer();
                orderTransfer.setOrderId(orderDetail.getSchoolId());
                orderTransfer.setOutSchoolId(orderDetail.getSchoolId());
                orderTransfer.setOutGradeId(orderDetailOld.getCourseId());
                orderTransfer.setInSchoolId(orderDetail.getCourseId());
                orderTransfer.setOutHouse(orderDetail.getResidueCourseCount());
                orderTransfer.setOutPrice(orderDetail.getResiduePrice());
                orderTransfer.setOutType(1);
                orderTransfer.setOrderType(3);
                orderTransfer.setVersion(afterVersion);
                iOrderTransferService.save(orderTransfer);

                OrderTransferDetail orderTransferDetail = new OrderTransferDetail();
                orderTransferDetail.setId(orderTransfer.getId());
                orderTransferDetail.setOrderType(orderApply.getOrderType());
                orderTransferDetail.setOrderId(orderApply.getId());//设置对应的新订单id
                orderTransferDetail.setOldOrderId(orderApplyOld.getId());
                orderTransferDetail.setOldOrderDetailId(orderDetailOld.getId());
                orderTransferDetail.setOutHouse(orderDetail.getResidueCourseCount());
                orderTransferDetail.setOutPrice(orderDetail.getResiduePrice());


                //转课，扣除原有课时
                if(orderDetailOld != null){
                    //全部转出，把课程设置为转出状态
                    StudentGrade studentGrade = studentGradeMapper.selectById(orderDetailOld.getId());
                    if(studentGrade != null){
                        if(studentGrade.getUseCourseCount() == 0){
                            //iStudentSchoolService.removeById(studentGrade);
                        }else {
                            //把所在班级设置为结课状态
                            UpdateWrapper<StudentGrade> studentGradeUpdateWrapper = new UpdateWrapper<>();
                            //studentGradeUpdateWrapper.set("status",2);
                            studentGradeUpdateWrapper.set("reading_status",ReadingStatusEnum.FINISH.getKey());
                            studentGradeUpdateWrapper.eq("order_detail_id",orderDetailOld.getId());
                            //iStudentGradeService.update(null,studentGradeUpdateWrapper);
                        }
                    }
                }
                orderTransferDetail.setVersion(afterVersion);
                iOrderTransferDetailService.save(orderTransferDetail);
                iOrderApplyService.save(orderApply);

                //结课
                j++;
                //System.out.println("count:"+count);
                //System.out.println("完成了i:"+j);
            }catch (Exception e){
                //System.out.println("报错：");
                //System.out.println(e.getMessage());
            }
            //courseQueryWrapper.eq()
            //Course course =
        }

    }

    @Override
    public List<OrderDetail> getOrderDetailForResidueCoruseCount(Integer yearPart, Integer quarterNum){
        return orderDetailMapper.getOrderDetailForResidueCoruseCount(yearPart,quarterNum);
    }

}
